<?php

Yii::import('common.models._base.BaseCourses');

class Courses extends BaseCourses {

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function rules() {
        return array(
            array('course_type_id, difficulty_type,category_id,classesTargetAudiences, course_titile,course_tag, course_short_description, course_description,course_outcome,course_prerequisites', 'required'),
            array('course_titile', 'length', 'max' => 145),
            array('classesTargetAudiences', 'type', 'type' => 'array', 'allowEmpty' => false),
            array('course_description, course_short_description, course_outcome, course_prerequisites, course_comment, course_other_information, create_time, update_time', 'safe'),
            array('course_titile, course_description, course_short_description,  course_outcome, course_prerequisites, course_comment, difficulty_type, course_other_information, certificate, status, create_time, update_time, backend_user_id, users_id', 'default', 'setOnEmpty' => true, 'value' => null),
            array('id, course_titile, course_description, course_short_description, course_outcome, course_prerequisites, course_comment, difficulty_type, course_other_information, certificate, status, create_time, update_time, course_type_id, category_id, backend_user_id, users_id', 'safe', 'on' => 'search'),
        );
    }

    public function attributeLabels() {
        return array(
            'course_titile' => Yii::t('app', 'Title'),
            'course_description' => Yii::t('app', 'Description'),
            'course_short_description' => Yii::t('app', 'Short Description'),
            'course_tag' => Yii::t('app', 'Tag'),
            'course_outcome' => Yii::t('app', 'Outcome'),
            'course_prerequisites' => Yii::t('app', 'Prerequisites'),
            'course_comment' => Yii::t('app', 'Comment'),
            'course_other_information' => Yii::t('app', 'Other Information'),
            'course_type_id' => Yii::t('app', 'Course Type'),
            'category_id' => Yii::t('app', 'Category'),
            'classesTargetAudiences' => Yii::t('app', 'Target Audience'),
        );
    }

    public function relations() {
        return array(
            'users' => array(self::BELONGS_TO, 'Users', 'users_id'),
            'courseType' => array(self::BELONGS_TO, 'ClassType', 'course_type_id'),
            'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
            'coursesStructures' => array(self::HAS_MANY, 'CoursesStructures', 'courses_id'),
            'backendUser' => array(self::BELONGS_TO, 'BackendUser', 'backend_user_id'),
            'classesTargetAudiences' => array(self::HAS_MANY, 'ClassesTargetAudience', 'courses_id'),
        );
    }

    public function search() {
        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id, true);
        $criteria->compare('course_titile', $this->course_titile, true);
        $criteria->compare('course_description', $this->course_description, true);
        $criteria->compare('course_short_description', $this->course_short_description, true);
        $criteria->compare('course_tag', $this->course_tag, true);
        $criteria->compare('course_outcome', $this->course_outcome, true);
        $criteria->compare('course_prerequisites', $this->course_prerequisites, true);
        $criteria->compare('course_comment', $this->course_comment, true);
        $criteria->compare('difficulty_type', $this->difficulty_type);
        $criteria->compare('course_other_information', $this->course_other_information, true);
        $criteria->compare('certificate', $this->certificate);
        $criteria->compare('status', $this->status);
        $criteria->compare('create_time', $this->create_time, true);
        $criteria->compare('update_time', $this->update_time, true);
        $criteria->compare('course_type_id', $this->course_type_id);
        $criteria->compare('category_id', $this->category_id);
        $criteria->compare('backend_user_id', $this->backend_user_id, true);
        $criteria->compare('users_id', $this->users_id);
        $criteria->order = 'create_time DESC';
        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    public static function deleteCoursesTargetAudience($courseId) {
        ClassesTargetAudience::model()->deleteAll('courses_id=:courses_id', array(':courses_id' => $courseId));
    }

    public static function deleteCoursesWithVenue($courseId) {
        CourseWithVenue::model()->deleteAll('courses_id=:courses_id', array(':courses_id' => $courseId));
    }

    public static function deleteCoursesBatches($courseId) {
        CourseBatche::model()->deleteAll('courses_id=:courses_id', array(':courses_id' => $courseId));
    }

    public static function deleteCoursesBatcheEarlyDiscount($courseId) {
        CourseEarlyDiscount::model()->deleteAll('courses_id=:courses_id', array(':courses_id' => $courseId));
    }

    public static function deleteCoursesBatcheGroupDiscount($courseId) {
        CourseGroupDiscount::model()->deleteAll('courses_id=:courses_id', array(':courses_id' => $courseId));
    }

    public static function contentRate($data) {
        $dataVal = ClassCourseContentLikeUnlike::model()->findByAttributes(array('courses_id' => $data->id));
        return (!empty($dataVal)) ? CHtml::link('Content-rate', Yii::app()->createUrl('courses/viewcontent', array("courseid" => $data->id))) : '-';
    }

    public static function deleteCoursesBatcheDaySessions($courseId) {
        CourseBatcheDaySession::model()->deleteAll('courses_id=:courses_id', array(':courses_id' => $courseId));
    }

    public static function deleteCoursesBatcheDateSessions($courseId) {
        CourseBatcheDateSession::model()->deleteAll('courses_id=:courses_id', array(':courses_id' => $courseId));
    }

    public static function deleteCoursesStructure($courseId) {
        ClassStructures::model()->deleteAll('courses_id=:courses_id', array(':courses_id' => $courseId));
    }

    public static function deleteClassFunLearning($courseId) {
        FunLearning::model()->deleteAll('courses_id=:course_id', array(':course_id' => $courseId));
    }

    public static function deleteClassTicketBooked($courseId) {
        TicketBooked::model()->deleteAll('courses_id=:courses_id', array(':courses_id' => $courseId));
    }

    public static function getTargetAudience($model) {
        $audienceName = '';
        $targetAudience = ClassesTargetAudience::model()->findAll('courses_id=:courses_id', array(':courses_id' => $model->id));
        foreach ($targetAudience as $value) {
            $audienceNames = TargetAudience::model()->findByPk($value['target_audience_id']);
            $audienceName.=$audienceNames->target_audience_name . ', ';
        }
        return substr($audienceName, 0, -3);
    }

    public static function getCourseWithVenues($courseId) {
        $courseWithVenue = CourseWithVenue::model()->findAll('courses_id=:courses_id', array(':courses_id' => $courseId));
        return $courseWithVenue;
    }

    public static function getCoursesBatch($courseId, $venueId) {
        $coursebatch = CourseBatche::model()->findAll('courses_id=:courses_id AND course_venue_id=:course_venue_id ', array(':courses_id' => $courseId, 'course_venue_id' => $venueId));
        return $coursebatch;
    }

    public static function getCourseBatchEarlyBirdDiscount($courseId, $bacthId) {
        $courseEarlyDiscount = CourseEarlyDiscount::model()->findAll('courses_id=:courses_id AND course_batche_id=:course_batche_id', array(':courses_id' => $courseId, 'course_batche_id' => $bacthId));
        return $courseEarlyDiscount;
    }

    public static function getCourseBatchGroupDscount($courseId, $bacthId) {
        $courseGroupDiscount = CourseGroupDiscount::model()->findAll('courses_id=:courses_id AND course_batche_id=:course_batche_id', array(':courses_id' => $courseId, 'course_batche_id' => $bacthId));
        return $courseGroupDiscount;
    }

    public static function getCourseWithImage($courseId) {
        $classWithImage = ClassImage::model()->findAll('courses_id=:courses_id', array(':courses_id' => $courseId));
        return $classWithImage;
    }

    public static function getCustomeSecheduleDaySession($courseId, $bacthId) {
        $customeSechedule = CourseBatcheDaySession::model()->findAll('courses_id=:courses_id AND course_batche_id=:course_batche_id ', array(':courses_id' => $courseId, 'course_batche_id' => $bacthId));
        return $customeSechedule;
    }

    public static function getSchedulename($scheduleId) {
        $name = ClassSchedule::model()->findByPk($scheduleId);
        echo $name->name;
    }

    public static function getCustomeSecheduledateSession($courseId, $bacthId) {
        $customeSechedule = CourseBatcheDateSession::model()->findAll('courses_id=:courses_id AND course_batche_id=:course_batche_id ', array(':courses_id' => $courseId, 'course_batche_id' => $bacthId));
        return $customeSechedule;
    }

    public static function getCourseStructure($courseId, $bacthId) {
        $courseStructure = ClassStructures::model()->findAll('courses_id=:courses_id AND course_batche_id=:course_batche_id ', array(':courses_id' => $courseId, 'course_batche_id' => $bacthId));
        return $courseStructure;
    }

    public static function CourseImageingridView($data) {
        $userId = ($data->courses->backend_user_id != '') ? 'backend/' . getLoginUserId() : $data->courses->users_id;
        return ROOT_IMAGE_PATH . SkillConfig::getClassCourseImagethumbsPath($userId) . $data->photo;
    }

    /* Skill::Gyan  this function use change status any table */

    public static function changeStatusIngridView($data) {
        return ($data->primary_image == 1) ? CHtml::image(baseUrl() . "/images/active.png", "Primary-image", array("title" => "Remove primary image", "style" => "cursor:pointer", "onclick" => "ChangeStatus(" . $data->id . ",$data->courses_id)")) : CHtml::image(baseUrl() . "/images/deactive.png", "Inactive", array("title" => "Mark Primary Image", "style" => "cursor:pointer", "onclick" => "ChangeStatus(" . $data->id . ",$data->courses_id)"));
    }

    public static function courseOtherInformation($classId) {
        $inormation = Courses::model()->findByPk($classId);
        return $inormation->course_other_information;
    }

    public static function checkQueryEmpty($data) {
        $dataVal = MakeQuery::model()->findByAttributes(array('courses_id' => $data->id));
        return ($dataVal != '') ? CHtml::link('View Query', Yii::app()->createUrl('makeQuery/admin', array('courseid' => $data->id))) : 'No Query';
    }

    public static function checkClassesReview($data) {
        $classCourseRatePostitve = ClassCourseTrainnerRate::model()->findByAttributes(array('courses_id' => $data->id));
        $dataVal = Reviews::model()->findByAttributes(array('courses_id' => $data->id));
        return ((!empty($dataVal)) || (!empty($classCourseRatePostitve))) ? CHtml::link('View', Yii::app()->createUrl('reviews/courseReviews', array("id" => $data->id))) : 'No Reviews';
    }
     public static function trainersuggest($data) {
        $tag = '';
        $localitys = '';
        $dataVal = count(ClassCourseTags::model()->findByAttributes(array('users_id' => $data->users_id, 'status' => SkillConfig::STATUS_DEACTIVE)));
        $tag = ($dataVal > 0) ? CHtml::link('Tag', Yii::app()->createUrl('classCourseTags/suggesttag', array("usersid" => $data->users_id,"type"=>'course'))) : '';
        $locality = count(LocalityName::model()->findByAttributes(array('users_id' => $data->users_id, 'status' => SkillConfig::STATUS_DEACTIVE)));
        if ($locality > 0) {
            $localitys = (!empty($locality)) ? CHtml::link('Locality', Yii::app()->createUrl('localityName/suggestlocalityname', array("usersid" => $data->users_id,"type"=>'course'))) : '';
        }
        return (!empty($tag) && !empty($localitys)) ? $localitys . '  /  ' . $tag : $localitys . '' . $tag;
    }
    public static function getStartDateByclass($courseId) {
        $date = date('Y-m-d');
        $startDate = '';
        $criteria = new CDbCriteria();
        $criteria->addCondition('courses_id="' . $courseId . '"');
        $criteria->addCondition('date_to>="' . $date . '"');
        $criteria->order = "date_from,'ASC'";
        $startDates = CourseBatche::model()->find($criteria);
        if ($startDates->date_to >= $date) {
            $startDate = date('D, d  M', strtotime($startDates->date_from)) . '    -    ' . date('D, d  M', strtotime($startDates->date_to));
        }

        $startDate = substr($startDate, 0, 1000);
        if (!empty($startDate)) {
            return $startDate;
        }
    }

    public static function getfunlearing($courseId) {
        $funlearing = FunLearning::model()->find('courses_id=:courses_id', array(':courses_id' => $courseId));
        return $funlearing;
    }

    public static function countCousrseBatchDateSession($courseId) {
        $dayNo = '';
        $criteria = new CDbCriteria();
        $criteria->select = 't.*';
        $criteria->join = 'LEFT JOIN skill_course_batche scb ON (t.course_batche_id = scb.id)';
        $criteria->addCondition('t.courses_id=' . $courseId);
        $batchDateSession = count(CourseBatcheDateSession::model()->findAll($criteria));
        $criteria = new CDbCriteria();
        $criteria->join = 'LEFT JOIN skill_course_batche scb ON (t.course_batche_id = scb.id)';
        $criteria->addCondition('t.courses_id=' . $courseId);
        $batchDaySessions = CourseBatcheDaySession::model()->findAll($criteria);

        foreach ($batchDaySessions as $batchDaySession) {
            $start = new DateTime($batchDaySession->courseBatche->date_from);
            $end = new DateTime($batchDaySession->courseBatche->date_to);
            $days = $start->diff($end, true)->days;
            if ($batchDaySession->schedule_id == 5) {
                $dayNo = 1;
            }
            if ($batchDaySession->schedule_id == 6) {
                $dayNo = 2;
            }
            if ($batchDaySession->schedule_id == 7) {
                $dayNo = 3;
            }
            if ($batchDaySession->schedule_id == 8) {
                $dayNo = 4;
            }
            if ($batchDaySession->schedule_id == 9) {
                $dayNo = 5;
            }
            if ($batchDaySession->schedule_id == 10) {
                $dayNo = 5;
            }
            if ($batchDaySession->schedule_id == 11) {
                $dayNo = 7;
            }
            $sundays = intval($days / $dayNo) + ($start->format('N') + $days % $dayNo >= $dayNo);

            $result[] = $sundays;
        }
        $daySession = count($result);

        if (!empty($daySession) && empty($batchDateSession)) {
            return '0 - ' . $daySession;
        }
        if (empty($daySession) && !empty($batchDateSession)) {
            return $daySession . ' - 0';
        }
        if ($batchDateSession >= $daySession) {
            return $batchDateSession . ' - ' . $daySession;
        }
        if ($batchDateSession <= $daySession) {
            return $batchDateSession . ' - ' . $daySession;
        }
    }

}
